package xdu.lz.stage1_basic.chapter3_threadCommunicate;


public class ProduceConsumer2 {
    private int i;
    private final Object LOCK = new Object();
    private volatile  boolean isProduced = false;
    public void produce(){
        synchronized (LOCK){
            //如果已经生产，等待消费完毕后被通知
            if(isProduced){
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            //如果没有生产，生产并通知消费者消费,并把生产置为true
            }else {
                System.out.println("生产->"+(++i));
                LOCK.notify();
                isProduced = true;
            }
        }
    }
    public void consume(){
        synchronized (LOCK){
            //如果已经生产了，则消费，然后通知生产者生产,并把已经生产置为false
            if(isProduced){
                System.out.println("消费->"+i);
                LOCK.notify();
                isProduced = false;
            //否则等待生产者生产 被通知
            }else {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ProduceConsumer2 pc = new ProduceConsumer2();
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                while (true){
                    pc.produce();
                }
            }).start();
            new Thread(() -> {
                while (true){
                    pc.consume();
                }
            }).start();
        }


    }
}
